/**
 * 服务端IP和端口是否可用计算
 */
package com.gomeplus.commons.quartz.netty;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gomeplus.commons.quartz.cache.QuartzPropertiesCache;
import com.gomeplus.commons.quartz.cache.ServerIpCache;

/**
 * @author chenmin-ds 服务端IP和端口是否可用计算
 */
public class ServerIpAndPortSet {

	private static Logger logger = LoggerFactory.getLogger("ServerIpAndPortCheckThread");

	private static int index = 0;

	/**
	 * @Title: setIpPort
	 * @Description: 设置端口号
	 * @return void 返回类型
	 */
	public static void setIpPort() {
		try {
			String[] ipPortArrays = QuartzPropertiesCache.getRemoteAddress().split(";");
			if (StringUtils.isEmpty(ServerIpCache.getNettyServerIp())) {
				check(ipPortArrays[index]);
			} else {
				index++;
				if (index == ipPortArrays.length) {
					index = 0;
				}
				check(ipPortArrays[index]);
			}
		} catch (Exception e) {
			logger.info("现有服务端IP[{}]和端口[{}]不可用，需要重新计算", ServerIpCache.getNettyServerIp(), ServerIpCache.getNettyServerPort() + "");
			ServerIpCache.setNettyServerStatus(false);
		}
	}

	private static void check(String ipPort) {
		try {
			String[] ipPorts = ipPort.split(":");
			ServerIpCache.setNettyServerIp(ipPorts[0].trim());
			ServerIpCache.setNettyServerPort(Integer.valueOf(ipPorts[1].trim()));
			ServerIpCache.setNettyServerStatus(true);
		} catch (Exception e) {
			logger.error("服务端IP和端口不可用，ipPort=" + ipPort, e);
			ServerIpCache.setNettyServerStatus(false);
		}
	}
}
